﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Golf.WebUI.Models
{
    using Core;

    public class EditPlayerViewModel
    {
        public EditPlayerViewModel(Player player, IEnumerable<County> counties)
        {
            Forename = player.Forename;
            Surname = player.Surname;
            GenderList = CreateEnumList<Gender>(player.Gender);
            Hometown = player.Hometown;
            CountyList = CreateCountySelectList(player, counties);
        }

        public string Forename { get; private set; }
        public string Surname { get; private set; }
        public IEnumerable<SelectListItem> GenderList { get; private set; }
        public string Hometown { get; private set; }
        public IEnumerable<SelectListItem> CountyList { get; private set; }

        private IEnumerable<SelectListItem> CreateCountySelectList(Player player, IEnumerable<County> counties)
        {
            return new List<County>(counties).ConvertAll<SelectListItem>(delegate(County toConvert)
            {
                SelectListItem county = new SelectListItem() { Text = toConvert.Name, Value = toConvert.Id.ToString() };
                if (object.Equals(toConvert, player.County))
                {
                    county.Selected = true;
                }
                return county;
            });
        }

        private IEnumerable<SelectListItem> CreateEnumList<T>(T selectedValue)
        {
            List<SelectListItem> selectListItems = new List<SelectListItem>();
            foreach (T value in Enum.GetValues(typeof(T)))
            {
                string text = Enum.GetName(typeof(T), value);
                bool selected = object.Equals(value, selectedValue);
                SelectListItem item = new SelectListItem() { Text = text, Value = value.ToString(), Selected = selected };
                selectListItems.Add(item);
            }
            return selectListItems;
        }
    }
}